//
//  BaseSelfDiagnosisService.m
//  MobileChecker
//
//  Created by Lymons on 15-1-8.
//  Copyright (c) 2015年 Lymons. All rights reserved.
//

#import "BaseSelfDiagnosisService.h"

@implementation BaseSelfDiagnosisService

- (RACDisposable *)startTimer:(id<RACSubscriber>)subscriber
{
    @weakify(self);
    self.timerDispose =  [[[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] takeUntil:[self rac_willDeallocSignal]] subscribeNext:^(NSDate *now) {
        @strongify(self);
        self.leftSeconds --;
        if (self.leftSeconds == 0) {
            [self endCheckOnTimer:subscriber];
            [subscriber sendNext:@(YES)];
            [subscriber sendCompleted];
        }
    }];
    
    return self.timerDispose;
}

- (RACSignal *)checkSignal:(NSUInteger)seconds
{
    self.leftSeconds = seconds;
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        if (self.leftSeconds > 0) {
            [self startTimer:subscriber];
        }
        
        [self startCheck:subscriber];
        
        return [RACDisposable disposableWithBlock:^{
            [self.timerDispose dispose];
            self.timerDispose = nil;
        }];
    }];
}

- (void)startCheck:(id<RACSubscriber>)subscriber
{
    // do something in subclass
}

- (void)endCheckOnTimer:(id<RACSubscriber>)subscriber
{
    [self.timerDispose dispose];
}

@end
